
#include "thread_manager.h"
#include "pcie_proce.h"
#include "sys_resource.h"

extern int thread_recv_pcie_signal;
void thread_manager(RecvCmd * recv_cmd) {
    prctl(PR_SET_NAME, "Manager");
    pthread_detach(pthread_self());  
    
    //申请内存资源
    BQueueBox * qBox = createBQueue(DATA_PCIE_BUFF_SIZE, PCIE_QUEUE_NUM, PCIE_QUEUE_EXTEN);
    PackWriteFile *pwf = apply_resource(PWF_SIZE, recv_cmd, qBox); 
    size_t i = 0;

#if     NO_PCIE
	//光纤数据处理
	pthread_t thread_recv_pcie_data_id;
	pthread_create(&thread_recv_pcie_data_id, NULL, thread_recv_pcie_data, (void *)pwf);
#endif

#if     NO_WLAN
    VlanData vdata[VALN_NUM] = { 0 };
    init_vdata(&vdata, pwf);            //初始化网络相关参数
    check_status_vdata(&vdata, pwf);    //检查网络状态并上报
#endif

#if     NO_PCIE    
    /** #备注: 释放资源, 前提是:写文件的线程都得以结束并释放资源 */
    pthread_join(thread_recv_pcie_data_id, NULL);   //PCIE
#endif

#if     NO_WLAN
    //网络
    for (i = 0;i < VALN_NUM; i++) {
        if(vdata[i].flag == VD_FLAG_ON) {
            pthread_join(vdata[i].thread_id, NULL);
        }               
    }
#endif
    //文件读写
    PackWriteFile *cpwf = pwf;
    for (i = 0; i < PWF_SIZE; i++) {
        pthread_join(cpwf->thread_id, NULL);
        *cpwf++;
    }

    //释放文件
    free_resource(pwf, pwf->qBox);
}

/** 处理协议指令**/ 
void del_cmd(RecvCmd *recv_cmd) {
    // LOG_DEBUG("指令: %02x \n", recv_cmd->luqu_status);
    
    if(recv_cmd->luqu_status == 0x01) {
        LOG_INFO("指令: 录取 \n");

        if(thread_recv_pcie_signal) {
            LOG_WARN("系统数据正在采集中... \n");
            return ;
        }

        long file_size = recv_cmd->FileSize * SIZE_GB;
        if(file_size == 0) {
            LOG_DEBUG("文件大小不限制 \n");
        }else{
            LOG_DEBUG("文件大小限制 %dGB \n", recv_cmd->FileSize);
        }
        //启动一个线程        
        thread_recv_pcie_signal = 1;        
        pthread_t thread_manager_id;
		// 启动管理线程
        RecvCmd * cmd = malloc(sizeof(RecvCmd));
        memset(cmd, 0x00, sizeof(RecvCmd));
        memcpy(cmd, recv_cmd, sizeof(RecvCmd));
        pthread_create(&thread_manager_id, NULL, thread_manager, (void *)cmd);
    }

    if(recv_cmd->luqu_status == 0x00) {
        LOG_INFO("指令: 结束 \n");
        thread_recv_pcie_signal = 0;
    }
}
